import json
import os

from flask import Blueprint, render_template, request, jsonify

from applications.common.utils.http import table_api, fail_api
from applications.extensions import db
from plugins.users.models.UserDepMap import UserDepMap
from plugins.users.models.User import User


dir_path = os.path.dirname(os.path.realpath(__file__)).replace("\\", "/")

bp = Blueprint('users_depmap', __name__, url_prefix='/depmap')



@bp.route('/', methods=['GET'])
def index():
    return render_template('admin/depmap/index.html')


@bp.route('/data', methods=['GET', 'POST'])
def data():
    depid = request.args.get('depid')
    d = db.session.query(
        UserDepMap, User
    ).outerjoin(
        User,UserDepMap.userid == User.id
    ).filter(
        UserDepMap.depid == depid
    ).order_by(UserDepMap.isleader.desc()).layui_paginate()
    if d:
        print(d)
        rdata = []
        for dm in d:
            print(dm)
        for dep, u in d:
            rdata.append({
                'id': dep.id,
                'userid': dep.userid,
                'username': u.username,
                'isleader': dep.isleader,
                'truename': u.truename
            })
        print(rdata)
        return table_api(data = rdata,count=d.total)
    else:
        return fail_api(msg='未找到数据')

@bp.route('/add', methods=['POST'])
def add():
    depid = request.form.get('depid') or 0
    data = request.form.get('data')
    if depid:
        da = json.loads(data)
        dd = UserDepMap()
        for d in da:
            # print(d)
            if dd.query.filter_by(depid=depid, userid=dd.userid).count() ==0:
                dd.depid = depid
                dd.userid = d['name']
                db.session.add(dd)
        db.session.commit()
        return jsonify({'code': 0, 'msg': '添加成功'})
    else:
        return fail_api(msg='部门ID不能为空，请先选择左侧的组织架构。')